package hello

import (
	"fmt"
	"html/template"
	"net/http"
//	"time"

	"appengine"
//	"appengine/datastore"
	"appengine/user"
)

func init() {
	http.HandleFunc("/", root)
	http.HandleFunc("/cheese", cheese)
	http.HandleFunc("/cheeseboard", cheeseboard)
}

func root (w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-type", "text/html; charset=utf-8")
	c := appengine.NewContext(r)
	u := user.Current(c)
	if u == nil {
		url, _ := user.LoginURL(c, "/")
		fmt.Fprintf(w, `<a href="%s">Sign in or register</a>`, url)
		return
	}
//	url, _ := user.LogoutURL(c, "/")
//	fmt.Fprintf(w, `Welcome, %s! (<a href="%s">sign out</a>)`, u, url)
	fmt.Fprint(w, cheeseHomePage)
}

const cheeseHomePage = `
<html>
	<head>
		<title>Cheese this sucker!</title>
	</head>
	<body>
		<form action="/cheese" method="post">
			<div><input type="text" name="user"></input><div>
			<div><input type="submit" value="Cheese this sucker!"></div>
		</form>
	</body>
</html>
`

func cheese(w http.ResponseWriter, r *http.Request) {
	err := cheeseTemplate.Execute(w, r.FormValue("content"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

var cheeseTemplate = template.Must(template.New("user").Parse(cheeseTemplateHTML))

const cheeseTemplateHTML = `
<html>
	<head>
		<title>You got cheesed.</title>
	</head>
	<body>
		<p>Someone cheesed you. That person was: {{.}}</p>
		<form action="/cheeseboard" method="post">
			<div><input type="submit" value="Go to the cheeseboard"></div>
		</form>
	</body>
</html>
`

func cheeseboard(w http.ResponseWriter, r *http.Request) {
	err := cheeseboardTemplate.Execute(w, r.FormValue("content"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

var cheeseboardTemplate = template.Must(template.New("user").Parse(cheeseboardTemplateHTML))

const cheeseboardTemplateHTML = `
<html>
	<head>
		<title>You got cheesed.</title>
	</head>
	<body>
		<p>Other people have been cheesed.</p>
		<p>It will not stop.</p>
		<p>...</p>
		<p><i>Run.</i></p>
	</body>
</html>
`